class TaiSan < ActiveRecord::Base
  attr_accessible :MaTS, :TenTS, :LoaiT_id, :DvTinh, :DonGia, :SLuong, :ThongsoKT, :NamSD
  belongs_to :loaiTS, :class_name => "LoaiT", :foreign_key => "LoaiT_id"
  has_many  :ct_phongs,  :class_name => "CtPhong"
  has_many  :phieu_nhaps, :class_name => "PhieuNhap"
  has_many  :phieu_xuats, :class_name => "PhieuXuat"
  has_many :nhat_kies, :foreign_key => "Tai_san_id", :primary_key => "MaTS"
  validates_length_of :MaTS, :in => 9..10, :allow_nil => false
  validates_uniqueness_of :MaTS
  validates_presence_of :TenTS, :LoaiT_id, :DvTinh, :DonGia, :NamSD

  # hàm truyền mảng dữ liệu thông qua format csv    EXPORT
  def self.to_csv(taisans, options = {})     # đối số taisans, gọi option để truyền vào từng cột trong excel
    CSV.generate(options) do |csv|
      csv << column_names
      taisans.each do |taisan|
        csv << taisan.attributes.values_at(*column_names)
      end
    end
  end
  # hàm truyền dữ liệu gọi lên vào database          IMPORT
  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      taisan = find_by_id(row["id"]) || new
      taisan.attributes = row.to_hash.slice(*accessible_attributes)
      return false if taisan.invalid?
      taisan.save!
    end
    true
  end
  # hàm truy xuất file upload lên
  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
      when '.csv' then Roo::Csv.new(file.path, nil, :ignore)
      when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
      when '.xlsx' then Roo::Excelx.new(file.path, nil, :ignore)
      else raise "Unknown file type: #{file.original_filename}"
    end
  end
end
